'use strict'
const { Products, Op } = require('../model')

let fn_get = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || '';
    console.log(keyword);
    if (keyword) {
        let list = await Products.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { productname: keyword },
                    { price: isNaN(keyword) ? 0 : parseInt(keyword) },
                ]
            }
        })
        ctx.body = list;
    } else {
        let list = await Products.findAll({
            order: ['id']
        });
        ctx.body = list
    }
}

let fn_post = async (ctx, next) => {
    let obj = ctx.request.body;

    await Products.create({
        productname: obj.productname,
        price: obj.price,
    })
    ctx.body = {
        code: 200,
        data: '',
        msg: '添加成功!'
    }
}

let fn_put = async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    await Products.update({
        productname: obj.productname,
        price: obj.price,
    },
        {
            where: {
                id: id
            }
        }
    )
    ctx.body = {
        code: 200,
        data: '',
        msg: '删除成功!'
    }
}

let fn_delete = async (ctx, next) => {
    let id = ctx.request.params.id;
    await Products.destroy({
        where: {
            id: id
        }
    });
    let list = await Products.findAll({
        order: ['id']
    });
    ctx.body = list;
}

module.exports = {
    "get /product": fn_get,
    "post /product": fn_post,
    "put /product/:id": fn_put,
    "delete /product/:id": fn_delete,
}